package com.fan.shop.views.bean;

import java.io.File;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
import javax.servlet.http.Part;

import org.apache.log4j.Logger;

import com.fan.shop.businesslogic.FileUploadProcess;
import com.fan.shop.businesslogic.ItemCreateProcess;
import com.fan.shop.global.ShopGlobalUtils;
import com.fan.shop.global.ShopGlobalVariables;
import com.fan.shop.model.commonbrowser.CommonBrowser;
import com.fan.shop.services.BrandService;
import com.fan.shop.services.CategoryService;
import com.fan.shop.services.ItemService;
import com.fan.shop.services.LocationService;
import com.fan.shop.services.TransactionReferenceService;

@ManagedBean(name = "createItemBean")
@RequestScoped
public class CreateItemBean extends ShopBean {

	private static Logger logger = Logger.getLogger(CreateItemBean.class);

	@ManagedProperty(value = "#{locationService}")
	private LocationService locationService;

	@ManagedProperty(value = "#{brandService}")
	private BrandService brandService;

	@ManagedProperty(value = "#{categoryService}")
	private CategoryService categoryService;

	@ManagedProperty(value = "#{transactionReferenceService}")
	private TransactionReferenceService transactionReferenceService;
	@ManagedProperty(value = "#{itemService}")
	private ItemService itemService;

	private ShopBean parentBean;

	private String itemName;
	private String itemDescription;
	private BigDecimal price;
	private String origLocation;
	private String category;
	private String icon;
	private Date registeredTime;
	private String attribute;
	private boolean suspended;
	private String brand;

	private String itemCode;
	private String transactionReferenceNumber;

	private Part iconFile;
	private String previewIconPath;
	private String tempIconFilePath;

	public CreateItemBean() {
		super();
		setReturnedValues();
	}

	public void setReturnedValues() {
		Map<String, Object> map = FacesContext.getCurrentInstance()
				.getExternalContext().getRequestMap();
		if (map.containsKey("common_browser")) {
			CommonBrowser commonBrowser = (CommonBrowser) map
					.get("common_browser");

			itemService = ((CreateItemBean) commonBrowser.getCaller())
					.getItemService();
			categoryService = ((CreateItemBean) commonBrowser.getCaller())
					.getCategoryService();
			locationService = ((CreateItemBean) commonBrowser.getCaller())
					.getLocationService();

			itemName = ((CreateItemBean) commonBrowser.getCaller())
					.getItemName();
			itemDescription = ((CreateItemBean) commonBrowser.getCaller())
					.getItemDescription();
			price = ((CreateItemBean) commonBrowser.getCaller()).getPrice();
			origLocation = ((CreateItemBean) commonBrowser.getCaller())
					.getOrigLocation();
			category = ((CreateItemBean) commonBrowser.getCaller())
					.getCategory();
			brand = ((CreateItemBean) commonBrowser.getCaller()).getBrand();
			previewIconPath = ((CreateItemBean) commonBrowser.getCaller())
					.getPreviewIconPath();
			icon = ((CreateItemBean) commonBrowser.getCaller()).getIcon();
			tempIconFilePath = ((CreateItemBean) commonBrowser.getCaller())
					.getTempIconFilePath();
			attribute = ((CreateItemBean) commonBrowser.getCaller())
					.getAttribute();
			suspended = ((CreateItemBean) commonBrowser.getCaller())
					.isSuspended();
			transactionReferenceNumber = ((CreateItemBean) commonBrowser
					.getCaller()).getTransactionReferenceNumber();

			parentBean = ((ShopBean) commonBrowser.getCaller()).getParentBean();

			if (commonBrowser.getTriggerField().equals("category_name")) {
				if (commonBrowser.getReturnList() != null
						&& commonBrowser.getReturnList().size() > 0) {
					int categoryID = Integer.parseInt(commonBrowser
							.getReturnList().get(0));
					category = categoryService.getCategory(categoryID)
							.getName();
				}
			}
			if (commonBrowser.getTriggerField().equals("location_name")) {
				if (commonBrowser.getReturnList() != null
						&& commonBrowser.getReturnList().size() > 0) {
					int origLocationID = Integer.parseInt(commonBrowser
							.getReturnList().get(0));
					origLocation = locationService.getLocation(origLocationID)
							.toString();
				}
			}
			if (commonBrowser.getTriggerField().equals("brand_name")) {
				if (commonBrowser.getReturnList() != null
						&& commonBrowser.getReturnList().size() > 0) {
					brand = commonBrowser.getReturnList().get(0);
				}
			}
			if (commonBrowser.getTriggerField().equals(
					"transaction_reference_name")) {
				if (commonBrowser.getReturnList() != null
						&& commonBrowser.getReturnList().size() > 0) {
					transactionReferenceNumber = commonBrowser.getReturnList()
							.get(0);
				}

			}

		}
	}

	public static Logger getLogger() {
		return logger;
	}

	public static void setLogger(Logger logger) {
		CreateItemBean.logger = logger;
	}

	public LocationService getLocationService() {
		return locationService;
	}

	public void setLocationService(LocationService locationService) {
		this.locationService = locationService;
	}

	public BrandService getBrandService() {
		return brandService;
	}

	public void setBrandService(BrandService brandService) {
		this.brandService = brandService;
	}

	public CategoryService getCategoryService() {
		return categoryService;
	}

	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}

	public TransactionReferenceService getTransactionReferenceService() {
		return transactionReferenceService;
	}

	public void setTransactionReferenceService(
			TransactionReferenceService transactionReferenceService) {
		this.transactionReferenceService = transactionReferenceService;
	}

	public ItemService getItemService() {
		return itemService;
	}

	public void setItemService(ItemService itemService) {
		this.itemService = itemService;
	}

	public ShopBean getParentBean() {
		return parentBean;
	}

	public void setParentBean(ShopBean parentBean) {
		this.parentBean = parentBean;
	}

	public String getItemName() {
		return itemName;
	}

	public void setItemName(String itemName) {
		this.itemName = itemName;
	}

	public String getItemDescription() {
		return itemDescription;
	}

	public void setItemDescription(String itemDescription) {
		this.itemDescription = itemDescription;
	}

	public BigDecimal getPrice() {
		return price;
	}

	public void setPrice(BigDecimal price) {
		this.price = price;
	}

	public String getOrigLocation() {
		return origLocation;
	}

	public void setOrigLocation(String origLocation) {
		this.origLocation = origLocation;
	}

	public String getCategory() {
		return category;
	}

	public void setCategory(String category) {
		this.category = category;
	}

	public String getIcon() {
		return icon;
	}

	public void setIcon(String icon) {
		this.icon = icon;
	}

	public Date getRegisteredTime() {
		return registeredTime;
	}

	public void setRegisteredTime(Date registeredTime) {
		this.registeredTime = registeredTime;
	}

	public String getAttribute() {
		return attribute;
	}

	public void setAttribute(String attribute) {
		this.attribute = attribute;
	}

	public boolean isSuspended() {
		return suspended;
	}

	public void setSuspended(boolean suspended) {
		this.suspended = suspended;
	}

	public String getBrand() {
		return brand;
	}

	public void setBrand(String brand) {
		this.brand = brand;
	}

	public String getItemCode() {
		return itemCode;
	}

	public void setItemCode(String itemCode) {
		this.itemCode = itemCode;
	}

	public String getTransactionReferenceNumber() {
		return transactionReferenceNumber;
	}

	public void setTransactionReferenceNumber(String transactionReferenceNumber) {
		this.transactionReferenceNumber = transactionReferenceNumber;
	}

	public Part getIconFile() {
		return iconFile;
	}

	public void setIconFile(Part iconFile) {
		this.iconFile = iconFile;
	}

	public String getPreviewIconPath() {
		return previewIconPath;
	}

	public void setPreviewIconPath(String previewIconPath) {
		this.previewIconPath = previewIconPath;
	}

	public String getTempIconFilePath() {
		return tempIconFilePath;
	}

	public void setTempIconFilePath(String tempIconFilePath) {
		this.tempIconFilePath = tempIconFilePath;
	}

	public void loadIconImage(AjaxBehaviorEvent event) {

		System.out.println(icon);

	}

	public String commitAction() {

		ItemCreateProcess itemCreateProcess = new ItemCreateProcess();
		itemCreateProcess.setCategoryService(categoryService);
		itemCreateProcess
				.setTransactionReferenceService(transactionReferenceService);
		itemCreateProcess.setLocationService(locationService);
		itemCreateProcess.setItemService(itemService);
		itemCreateProcess
				.setTransactionReferenceNumber(transactionReferenceNumber);
		itemCreateProcess.setItemName(itemName);
		itemCreateProcess.setItemDescription(itemDescription);
		itemCreateProcess.setPrice(price);
		itemCreateProcess.setItemOrigLocation(locationService
				.getLocationByValue(origLocation).getId());
		itemCreateProcess.setItemCategory(categoryService.getCategory(category)
				.getId());

		itemCreateProcess.setIconTempFile(new File(tempIconFilePath));
		itemCreateProcess.setItemAttributes(attribute);
		if (suspended) {
			itemCreateProcess.setSuspended(1);
		} else {
			itemCreateProcess.setSuspended(0);
		}
		
		itemCreateProcess.setBrand(brand);
		itemCreateProcess.setBrandService(brandService);
		
		int result = itemCreateProcess.process();

		if (result == ShopGlobalVariables.FAILED) {
			return "items.faces";
		} else {
			return "items.faces";
		}
	}

	public String loadIconAction() {
		FileUploadProcess fileUploadProcess = new FileUploadProcess();
		fileUploadProcess.setFileName("temp");
		fileUploadProcess.setPart(iconFile);
		fileUploadProcess.setUploadType(ShopGlobalVariables.TEMP);
		fileUploadProcess.setFileContentType(ShopGlobalUtils
				.getFileContentType(previewIconPath));
		int result = fileUploadProcess.process();
		if (result == ShopGlobalVariables.SUCCESS) {
			previewIconPath = fileUploadProcess.getRelativePath();
			icon = previewIconPath;
		} else {
			System.out.println(icon);
		}
		tempIconFilePath = fileUploadProcess.getFullFilePath();

		return "create_item.faces";
	}

	public String backToItemsAction() {

		return "items.faces";
	}

	public String openCategoriesAction() {
		CommonBrowser commonBrowser = new CommonBrowser();
		commonBrowser.setTriggerField("category_name");
		commonBrowser.setParentPage("../../views/management/create_item.faces");
		commonBrowser.setSelectionMode("single");
		commonBrowser.setShopService(categoryService);
		commonBrowser.setCaller(this);
		FacesContext.getCurrentInstance().getExternalContext().getRequestMap()
				.put("common_browser", commonBrowser);
		return "../../views/commonbrowser/commonbrowser.faces";

	}

	public String openLocationsAction() {
		CommonBrowser commonBrowser = new CommonBrowser();
		commonBrowser.setTriggerField("location_name");
		commonBrowser.setParentPage("../../views/management/create_item.faces");
		commonBrowser.setSelectionMode("single");
		commonBrowser.setShopService(locationService);
		commonBrowser.setCaller(this);
		FacesContext.getCurrentInstance().getExternalContext().getRequestMap()
				.put("common_browser", commonBrowser);
		return "../../views/commonbrowser/commonbrowser.faces";
	}

	public String openBrandsAction() {
		CommonBrowser commonBrowser = new CommonBrowser();
		commonBrowser.setTriggerField("brand_name");
		commonBrowser.setParentPage("../../views/management/create_item.faces");
		commonBrowser.setSelectionMode("single");
		commonBrowser.setShopService(brandService);
		commonBrowser.setCaller(this);
		FacesContext.getCurrentInstance().getExternalContext().getRequestMap()
				.put("common_browser", commonBrowser);
		return "../../views/commonbrowser/commonbrowser.faces";
	}

	public String openTransactionReferencesAction() {
		CommonBrowser commonBrowser = new CommonBrowser();
		commonBrowser.setTriggerField("transaction_reference_name");
		commonBrowser.setParentPage("../../views/management/create_item.faces");
		commonBrowser.setSelectionMode("single");
		transactionReferenceService
				.setGroupCode(ShopGlobalVariables.ITEM_GROUP);
		commonBrowser.setShopService(transactionReferenceService);
		commonBrowser.setCaller(this);
		FacesContext.getCurrentInstance().getExternalContext().getRequestMap()
				.put("common_browser", commonBrowser);
		return "../../views/commonbrowser/commonbrowser.faces";
	}

}
